<?php

/**
 * @Author: chenjianghui
 * @Date:   2018-08-07 10:53:30
 * @Last Modified by:   chenjianghui
 * @Last Modified time: 2018-08-09 10:43:21
 */
namespace app\common\model;

use think\Model;

class VerifyCode extends Model
{
    const CODE_STATUS_UNUSED      = 0; //未使用
    const CODE_STATUS_USE_SUCCESS = 1; //验证通过
    const CODE_STATUS_USE_FAILED  = 2; //验证失败  或者 验证码失效

    /**
     * 获取该用户还未使用的验证码
     * @Author   chenjianghui
     * @DateTime 2018-08-07T11:22:38+0800
     * @param    string                   $auth_type 验证码类型
     * @param    string                   $mobile    用户手机
     * @return   string                              bool
     */
    public static function getEffectiveCode($auth_type, $mobile)
    {
        $codeObj = model('verify_code')->where('targetno', $mobile)->where('auth_type', $auth_type)->where('status', self::CODE_STATUS_UNUSED)->find();
        //dump($codeObj);exit;
        if ($codeObj) {
            return $codeObj;
        }
        return false;
    }

    /**
     * 生成随机验证码
     */
    public static function getCode()
    {
        return rand(100000, 999999);
        //return 999999;
    }

    /**
     * 新增验证码
     * @Author   chenjianghui
     * @DateTime 2018-08-07T11:23:33+0800
     * @param    [type]                   $data 添加数据
     */
    public static function add($data)
    {
        try {
            $codeObj = self::getEffectiveCode($data['auth_type'], $data['mobile']);
            $data['code'] = self::getCode();
            $data['create_time'] = time();
            $data['auth_time'] = 0;
            $data['ip'] = request()->ip();
            if(!$data["source"]){
                $data["source"] = "web";
            }
            if ($codeObj){
                $res = $codeObj->allowField(true)->save($data);
            } else{
                $data['targetno'] = $data['mobile'];
                $codeObj = new VerifyCode($data);
                $res = $codeObj->allowField(true)->save();
            }
            if ($res){
                return $codeObj->code;
            } else{
                return false;
            }
        } catch (\Exception $e){
            return false;
        }
    }

    /**
     * 修改验证码状态--成功
     * @Author   chenjianghui
     * @DateTime 2018-08-07T11:25:09+0800
     * @param    array                    $data [description]
     * @return   [type]                         [description]
     */
    public function toSuccess($data = array())
    {
        $this->status    = self::CODE_STATUS_USE_SUCCESS;
        $this->auth_time = time();
        if ($data['uid']) {
            $this->uid = $data['uid'];
        }
        $this->save();
    }

    /**
     * 验证码废弃
     * @Author   chenjianghui
     * @DateTime 2018-08-07T11:52:17+0800
     * @return   [type]                   [description]
     */
    public static function toDisable($code_obj)
    {
        $code_obj->status = self::CODE_STATUS_USE_FAILED;
        $code_obj->save();
    }

    /**
     * 校验验证码
     * @Author   chenjianghui
     * @DateTime 2018-08-07T11:24:04+0800
     * @param    [type]                   $auth_type 认证类型：register_mobile（手机号注册）、login_mobile（手机号快捷登录）、find_password_mobile（手机号找回密码）
     * @param    [type]                   $mobile    手机账号
     * @param    [type]                   $code      验证码
     */
    public static function checkCode($auth_type, $mobile, $code)
    {
        $code_obj = self::getEffectiveCode($auth_type, $mobile);
        if ($code_obj) {
            $exist_time = time() - $code_obj->create_time;
            if ($exist_time > config('app.sms_code_expire_time')) {
                self::toDisable($code_obj);
                renderJson('验证码已失效，请重新获取', 0);
            } elseif ($code_obj->code != $code) {
                renderJson('验证码错误', 0);
            }
        } else {
            renderJson('验证码失效，请重新获取', 0);
        }
        return $code_obj;
    }
}
